package vip.xiaonuo.modular.manage.bicouponwrite.Listener;

import cc.blynk.clickhouse.ClickHouseConnection;
import cc.blynk.clickhouse.ClickHouseDataSource;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import vip.xiaonuo.modular.common.LoadClickhouseDatasource;
import vip.xiaonuo.modular.manage.bicouponwrite.entity.BiCouponWrite;
import vip.xiaonuo.modular.manage.bicouponwrite.service.BiCouponWriteService;
import vip.xiaonuo.util.GenerateUniqueIdUtil;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BiCouponWriteListener extends AnalysisEventListener<BiCouponWrite> {

    private final static int MAX_LIST_SIZE = 100;

    private List<BiCouponWrite> couponWrites1 = new ArrayList<>(MAX_LIST_SIZE);
    private List<BiCouponWrite> couponWrites = new ArrayList<>();

    private BiCouponWriteService biCouponWriteService;

    private ClickHouseConnection connection = null;

    //手动传入service对象
    public BiCouponWriteListener(BiCouponWriteService biCouponWriteService) {
        this.biCouponWriteService = biCouponWriteService;
    }

    @Override
    public void invoke(BiCouponWrite biCouponWrite, AnalysisContext analysisContext) {

        if (StringUtils.isNotBlank(biCouponWrite.getActivityName())){
            couponWrites.add(biCouponWrite);
        }
//        if (couponWrites.size() == MAX_LIST_SIZE){
//            try {
//                ClickHouseDataSource clickHouseDataSource = LoadClickhouseDatasource.get();
//                connection = clickHouseDataSource.getConnection();
//                connection.setAutoCommit(false);
//                ClickHouseConnection finalConnection = connection;
//                addClickHouse(couponWrites,finalConnection);
//            } catch (Exception e) {
//                log.error(couponWrites.get(0) + " >>> 添加失败", e);
//            } finally {
//                if (connection != null) {
//                    try {
//                        connection.close();
//                    } catch (SQLException ignore) {
//                    }
//                }
//            }
//            couponWrites = new ArrayList<>(MAX_LIST_SIZE);
//        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//        if (couponWrites.size() < MAX_LIST_SIZE){
//            try {
//                ClickHouseDataSource clickHouseDataSource = LoadClickhouseDatasource.get();
//                connection = clickHouseDataSource.getConnection();
//                connection.setAutoCommit(false);
//                ClickHouseConnection finalConnection = connection;
//                addClickHouse(couponWrites,finalConnection);
//            } catch (Exception e) {
//                log.error(couponWrites.get(0) + " >>> 添加失败", e);
//            } finally {
//                if (connection != null) {
//                    try {
//                        connection.close();
//                    } catch (SQLException ignore) {
//                    }
//                }
//            }
//        }


        try {
                ClickHouseDataSource clickHouseDataSource = LoadClickhouseDatasource.get();
                connection = clickHouseDataSource.getConnection();
                connection.setAutoCommit(false);
                ClickHouseConnection finalConnection = connection;
                addClickHouse(couponWrites,finalConnection);
            } catch (Exception e) {
                log.error(couponWrites.get(0) + " >>> 添加失败", e);
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException ignore) {
                    }
                }
            }
        log.info("解析成功...");
    }

    final String insertSql = "insert into bi_coupon_write" +
            "" +
            "values (?, ?, ? , ? , ? , ? , ? , ? , ? ,?)";

    public void addClickHouse(List<BiCouponWrite> list , ClickHouseConnection connection) {
        // 注意这里使用的CK自己实现的PreparedStatement
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(insertSql);
            for (BiCouponWrite biCouponWrite : list) {
                preparedStatement.setLong(1, Long.parseLong(GenerateUniqueIdUtil.getGuid()));
                preparedStatement.setString(2, biCouponWrite.getStoreName());
                preparedStatement.setString(3, biCouponWrite.getWriteStoreId());
                preparedStatement.setString(4, biCouponWrite.getActivityName());
                preparedStatement.setString(5, biCouponWrite.getCouponName());
                preparedStatement.setString(6, biCouponWrite.getActivityType());
                preparedStatement.setBigDecimal(7, biCouponWrite.getOrderAmount());
                preparedStatement.setString(8 , biCouponWrite.getOrderNumber());
                preparedStatement.setString(9 , biCouponWrite.getOrgCode());
//
                Long time = new java.util.Date().getTime();
                if (StringUtils.isNotBlank(biCouponWrite.getOrderTime())){
                    if (biCouponWrite.getOrderTime().contains("/")){
                        time = Date.valueOf(biCouponWrite.getOrderTime().replace("/", "-")).getTime();
                    }else{
                        String orderTime = biCouponWrite.getOrderTime().split(" ")[0];
                        time = Date.valueOf(orderTime).getTime();
                    }
                }
                preparedStatement.setTimestamp(9 ,new Timestamp(time+28800000));
//                preparedStatement.setDate(10 ,new java.sql.Date(biCouponWrite.getOrderTime().getTime()));
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
            connection.commit();
        } catch (SQLException e) {
            log.error(list.get(0).getCouponName() + ">>>写入数据库失败", e);
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }
}
